;
(function (window, angular) {
    'use strict';
    angular.module("Controller.WorkBoard", [])
        .config(['$stateProvider', function ($stateProvider) {

            $stateProvider.state("app.workBoard.main", {
                is18n: true,
                url: "/main",
                templateUrl: "view/workBoard/main.html",
                controller: "MainCtrl"
            });

        }])

        .controller("MainCtrl", ["$scope", "ybHttp", "ybWidget", 'ybConfig', "$state", "EventBus", "MESG_TYPE", function ($scope, ybHttp, ybWidget, ybConfig, $state, EventBus, MESG_TYPE) {
            $scope.backlogData = {
                threeGuaranteesCount: 0,
                purchaseCount: 0,
                saleReturnCount: 0,
                dealerCount: 0,
                saleReverseCount: 0,
                lackInboundCount: 0,
                splitArrivalCount: 0,

                stockAlarmListCount: 0,
                deliveryNoteCount: 0,
            };
            $scope.btnPermission = {
                guaranteesApply: false,
                purchaseApply: false,
                returnApply: false,
                checkAgentApply: false,
                missNote: false,
                splitArrival: false,
                sapErrorList: false,
                libraryAge: false,
                deliveryNote: false,
                pickingBill: false,
                unusualOut: false,
                unusualIn: false,
            };
            var btnPermission = {
                guaranteesApply: "app.sales.guaranteesApply",
                purchaseApply: "app.sales.purchaseApply",
                returnApply: "app.sales.returnApply",
                checkAgentApply: "app.sales.client",
                missNote: "app.report.missNote",
                splitArrival: "app.stock.splitArrival",
                sapErrorList: "app.report.sapErrorList",
                libraryAge: "app.report.libraryAge",
                deliveryNote: "app.sales.deliveryNotice",
                pickingBill: "app.stock.pickingBill",
                unusualOut: "app.stock.unusualOut",
                unusualIn: "app.stock.unusualIn",
            };

            $scope.getSubNav = function (navName) {
                if (navName == 'purchaseRequestAlertForOneDay'){
                    $state.go("app.sales.purchaseApply",{notReviewedForOneDayCond:true});
                }else if (navName == 'purchaseRequestAlertForOneMonth'){
                    console.log("purchaseRequestAlertForOneMonth");
                    $state.go("app.sales.purchaseApply",{notEndedForOver1MonthCond:true});
                }else if (navName == 'saleOrderWarning'){
                    console.log("销售订单预警");
                    $state.go('app.sales.sellIntention',{flag:true})
                }else if (navName == 'deliveryNoticeWarning'){
                    console.log("发货通知单预警");
                    $state.go("app.sales.deliveryNotice",{flag:true});
                }else if (navName == 'orderMonitoring'){
                    console.log("订单监控");
                    $state.go('app.sales.sellIntention',{isOrderMonitoring:true})
                }
                else {
                    EventBus.Publish('go2otherMenuPage', { name: navName });
                }

            };

            /**
             * //获取近12月日期////
             * @returns {*[]}
             */
            function getLast12Month() {
                const curDate = new Date();
                const monthArr = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];

                const curYearNum = curDate.getFullYear();
                const curMonthIndex = curDate.getMonth();
                return monthArr.splice(curMonthIndex + 1).map(lm => `${curYearNum - 1}年${lm}`).concat(monthArr.map(jm => `${curYearNum}年${jm}`))
            }

            function getData() {
                var service = "device";
                var reqUrl = "/workBoard/workMain";
                var param = {};
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.backlogData.threeGuaranteesCount = resp.value.threeGuaranteesCount;
                    if (resp.value.threeGuaranteesCount > 99) {
                        $scope.backlogData.threeGuaranteesCount = "99+";
                    }
                    $scope.backlogData.purchaseCount = resp.value.purchaseCount;
                    if ($scope.backlogData.purchaseCount > 99) {
                        $scope.backlogData.purchaseCount = "99+";
                    }
                    $scope.backlogData.saleReturnCount = resp.value.saleReturnCount;
                    if ($scope.backlogData.saleReturnCount > 99) {
                        $scope.backlogData.saleReturnCount = "99+";
                    }
                    $scope.backlogData.dealerCount = resp.value.dealerCount;
                    if ($scope.backlogData.dealerCount > 99) {
                        $scope.backlogData.dealerCount = "99+";
                    }
                    $scope.backlogData.saleReverseCount = resp.value.saleReverseCount;
                    if ($scope.backlogData.saleReverseCount > 99) {
                        $scope.backlogData.saleReverseCount = "99+";
                    }

                    $scope.backlogData.lackInboundCount = resp.value.lackInboundCount;
                    if ($scope.backlogData.lackInboundCount > 99) {
                        $scope.backlogData.lackInboundCount = "99+";
                    }

                    $scope.backlogData.splitArrivalCount = resp.value.splitArrivalCount;
                    if ($scope.backlogData.splitArrivalCount > 99) {
                        $scope.backlogData.splitArrivalCount = "99+";
                    }

                    getStockAlarmListCount().then(function (data) {
                        if (!data) {
                            $scope.backlogData.stockAlarmListCount = 0;
                            return;
                        }
                        $scope.backlogData.stockAlarmListCount = data;
                        if ($scope.backlogData.stockAlarmListCount > 99) {
                            $scope.backlogData.stockAlarmListCount = "99+";
                        }
                    });
                    getDeliveryNoteCount().then(function (data) {
                        if (!data) {
                            $scope.backlogData.deliveryNoteCount = 0;
                            return;
                        }
                        $scope.backlogData.deliveryNoteCount = data;
                        if ($scope.backlogData.deliveryNoteCount > 99) {
                            $scope.backlogData.deliveryNoteCount = "99+";
                        }
                    });
                    getPickingBillCount().then(function (data) {
                        if (!data) {
                            $scope.backlogData.pickingBillCount = 0;
                            return;
                        }
                        $scope.backlogData.pickingBillCount = data;
                        if ($scope.backlogData.pickingBillCount > 99) {
                            $scope.backlogData.pickingBillCount = "99+";
                        }
                    });
                    getUnusualOutCount().then(function (data) {
                        if (!data) {
                            $scope.backlogData.unusualOutCount = 0;
                            return;
                        }
                        $scope.backlogData.unusualOutCount = data;
                        if ($scope.backlogData.unusualOutCount > 99) {
                            $scope.backlogData.unusualOutCount = "99+";
                        }
                    });
                    getUnusualInCount().then(function (data) {
                        if (!data) {
                            $scope.backlogData.unusualInCount = 0;
                            return;
                        }
                        $scope.backlogData.unusualInCount = data;
                        if ($scope.backlogData.unusualInCount > 99) {
                            $scope.backlogData.unusualInCount = "99+";
                        }
                    });

                    $scope.specialScore.series[0].data = resp.value.monthlySaleAmont;
                    $scope.specialScore.series[1].data = resp.value.monthlyReturnAmont;
                });
            }

            function getChartData(type) {
                var service = "device";
                var reqUrl = "/warehouseInventory/history/report";
                var param = {
                    type: type
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var chartData = (resp.value && resp.value.data && resp.value.data.length > 0) ? resp.value.data : [];
                    var chartLegendNames = (resp.value && resp.value.months && resp.value.months.length > 0) ? resp.value.months : [];
                    switch(type) {
                        case 0:
                            $scope.stockAmount.legend.data = chartData.map(item=>item.warehouseTypeName);
                            $scope.stockAmount.xAxis[0].data = chartLegendNames;
                            $scope.stockAmount.series = chartData.map(item=>{item.type="bar";item.name=item.warehouseTypeName;return item});
                            break;
                        case 1:
                            $scope.stockMoney.legend.data = chartData.map(item=>item.warehouseTypeName);
                            $scope.stockMoney.xAxis[0].data = chartLegendNames;
                            $scope.stockMoney.series = chartData.map(item=>{item.type="bar";item.name=item.warehouseTypeName;return item});
                            break;
                    }
                })
            }

            $scope.libraryAge = {
                chartTitle: '库龄分析',
                yData:[]
            };
            function getLibraryAgeData() {
                var service = "device";
                var reqUrl = "/report/libraryAgeQuantity";
                ybHttp.Get(service, reqUrl, {}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var dataT = [];
                    Object.keys(resp.value).forEach(function (key) {
                        dataT.push({ name: key, value: resp.value[key]})
                    })
                    $scope.libraryAge.yData = dataT;
                })
            }
            function getStockAlarmListCount() {
                var service = "device";
                var reqUrl = "/report/libraryAge/warn";
                return ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    return resp.value;
                });
            }
            function getDeliveryNoteCount() {
                var service = "device";
                var reqUrl = "/deliveryNote/mainBoardWaitAudit";
                return ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    return resp.value;
                });
            }
            function getPickingBillCount() {
                var service = "device";
                var reqUrl = "/materialsSchedule/mainBoardWaitAudit";
                return ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    return resp.value;
                });
            }
            function getUnusualOutCount() {
                var service = "device";
                var reqUrl = "/abnormalOut/mainBoardWaitAudit";
                return ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    return resp.value;
                });
            }
            function getUnusualInCount() {
                var service = "device";
                var reqUrl = "/abnormalIn/mainBoardWaitAudit";
                return ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    return resp.value;
                });
            }
            function getMenuList() {
                var service = "auth";
                var reqUrl = "/menu/listAuthorized";
                ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    checkBtnPermission(resp.value);
                });
            }

            function checkBtnPermission(permissionMenu) {
                for (var key in btnPermission) {
                    for (var i = 0, len = permissionMenu.length; i < len; i++) {
                        if (btnPermission[key] == permissionMenu[i].state) {
                            $scope.btnPermission[key] = true;
                            break;
                        }
                        if ('015' === permissionMenu[i].code) {
                            $scope.showNotify = true;
                        }
                        $scope.btnPermission[key] = false;
                    }
                }
            }


            /**
             * ***************************************** 通知公告及评论 开始 *****************************************
             */
            $scope.activeFlag = [true, false, false, false, false];
            $scope.noticeList = [];
            $scope.moreNoticList = [];
            $scope.noticeInfoObj = {};
            $scope.commentObj = {};
            $scope.commentList = [];
            $scope.showComponentBtn = false;
            $scope.showNotify = false;
            var commentId = "";
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.commentPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    default:
                        break;
                }
            };

            //获取首页面板中公告list
            function getNoticeBulletinList(pageSize) {
                var service = "device";
                var reqUrl = "/basicAnnouncement/listByDealer";
                var param = {
                    filters: {},
                    pageSize: 5,
                    pageNum: 1
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.noticeList = resp.value.list;
                });
            }

            function getMoreNoticeBulletinList(curPage) {
                var service = "device";
                var reqUrl = "/basicAnnouncement/listByDealer";
                var param = {
                    filters: {},
                    pageSize: 10,
                    pageNum: 1
                };
                param.pageSize = $scope.pageInfo.pageSize;
                param.pageNum = $scope.pageInfo.curPage;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.moreNoticList = resp.value.list;
                });
            }

            $scope.checkMore = function () {
                getMoreNoticeBulletinList();
                $scope.changeTab(1);
            };

            //跳转详情页面
            $scope.goDetail = function (id) {
                commentId = id;
                getDetail(id).then(function (data) {
                    $scope.noticeInfoObj = data.value;
                    return getEnclosureList(id)
                }).then(function (resp) {
                    $scope.noticeInfoObj.basicAttachmentList = resp.value.list;
                    return getCommentList(id);
                }).then(function (resp) {
                    $scope.changeTab(2);
                });
            };

            $scope.downloadAttach = function (item) {
                if(window.ZX_ORG_IDs.includes(item.orgId)){
                    window.location.href = ybHttp.RequestUrl("", "zx/basicAnnouncement/downloadAttach") + '?name=' + item.value + "&oldName=" + item.name;
                }else{
                    window.location.href = ybHttp.RequestUrl("device", "/basicAnnouncement/downloadAttach") + '?name=' + item.value + "&oldName=" + item.name;
                }

            };

            //获取附件列表
            var getEnclosureList = function (id) {
                var service = "device";
                var reqUrl = "/basicAttachment/list";
                var param = {
                    filters: {
                        announcementId: id
                    },
                    pageNum: 1,
                    pageSize: 10
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp;
                });
            };

            function getDetail(id) {
                var service = "device";
                return ybHttp.Get(service, "/basicAnnouncement/item", {
                    id: id
                }).then(function (data) {
                    if (data.code !== 0) {
                        ybWidget.ShowMessage(data.message);
                        return;
                    }
                    return data;
                });
            }


            //提交评论
            $scope.submitComment = function (id) {
                $scope.showComponentBtn = false;
                if (!$scope.commentObj.content) {
                    ybWidget.ShowMessage("评论内容为空，不可提交评论", MESG_TYPE.Error);
                    return;
                }

                submitComment(id).then(function () {
                    getCommentList(id);
                })
            };

            function submitComment(id) {
                var service = "device";
                var reqUrl = "/basicComment/add";
                var param = {};
                param.announcementId = id;
                param.content = $scope.commentObj.content;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp;
                });
            }

            //获取评论列表
            function getCommentList(id, curPage) {
                var service = "device";
                var reqUrl = "/basicComment/list";
                var param = {
                    filters: {}
                };
                param.pageSize = $scope.commentPageInfo.pageSize;
                param.pageNum = $scope.commentPageInfo.curPage;
                if (!!curPage) {
                    $scope.commentPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.commentPageInfo.curPage;
                param.filters.announcementId = id;


                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.commentPageInfo.totalRows = resp.value.total;
                    $scope.commentPageInfo.totalPages = resp.value.pages;
                    $scope.commentList = resp.value.list;
                });
            }

            //公告详情中的分页
            $scope.commentSearch = function () {
                getCommentList(commentId);
            };

            //系统公告页面列表的分页
            $scope.commentListSearch = function () {
                getMoreNoticeBulletinList();
            };

            //点击发表评论按钮
            $scope.showComponentBtnFn = function () {
                $scope.commentObj = {};
                $scope.showComponentBtn = !$scope.showComponentBtn;
            };
            /**
             * ***************************************** 通知公告及评论 结束 *****************************************
             */

            $scope.specialScore = {
                title: {
                    text: '前12个月销售量和退回量'
                },
                legend: {
                    data: ['销售量', '退回量']
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLabel: {
                            interval: 0
                        },
                        data: getLast12Month()
                    }
                ],
                series: [{ name: '销售量', type: 'bar' },{ name: '退回量', type: 'bar' }]
            };

            $scope.stockAmount = {
                title: {
                    text: '近一年库存数量'
                },
                legend: {
                    data: []
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLabel: {
                            interval: 0
                        },
                        data: []
                    }
                ],
                series: []
            };
            $scope.stockMoney = {
                title: {
                    text: '近一年库存金额'
                },
                legend: {
                    data: []
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLabel: {
                            interval: 0
                        },
                        data: []
                    }
                ],
                series: []
            };

            $scope.purchaseArrivalRate = {
                title: {
                    text: '采购订单到货率'
                },
                legend: {
                    data: ['到货率']
                },
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}%'
                        }
                    }
                ],
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}%'
                },
                tooltip: {
                    show: true,
                    formatter: '{b}<br/>{a}：{c}%'
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLabel: {
                            interval: 0
                        },
                        data: []
                    }
                ],
                series: [{ type:'bar', name: '到货率' }]
            };
            function getPurchaseArrivalRateData() {
                var service = "device";
                var reqUrl = "/purchaseRequest/timelyDeliveryChart";
                var param = {};
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    const resT = resp.value || {}

                    $scope.purchaseArrivalRate.xAxis[0].data = resT.monthList || [];
                    $scope.purchaseArrivalRate.series[0].data = resT.timelyQtyRateList || [];
                })
            }

            $scope.isEnvProd = ybConfig.isEnvProd();

            (function () {
                getData();
                if ($scope.isTJ) {
                    getChartData(0);
                    getChartData(1);
                }
                //getLibraryAgeData(); // 接口太慢，暂时注释，后期再考虑何时调用
                getNoticeBulletinList();
                getMenuList();

                if ($scope.isSCH) {
                    getPurchaseArrivalRateData()
                }
            })();

        }]);
})(window, window.angular);
